package com.wit.witmg.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wit.witmg.entity.TProdmater;
import com.wit.witmg.entity.TProdproc;
import com.wit.witmg.entity.TProdstat;
import com.wit.witmg.entity.TProdtech;
import com.wit.witmg.mapper.TProdprocMapper;
import com.wit.witmg.service.ITProdprocService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wit.witmg.service.ITProdstatService;
import com.wit.witmg.service.ITProdtechService;
import com.wit.witmg.util.ErrorCode;
import com.wit.witmg.util.JsonResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bob
 * @since 2025-01-09
 */
@Service
@RequiredArgsConstructor
public class TProdprocServiceImpl extends ServiceImpl<TProdprocMapper, TProdproc> implements ITProdprocService {
    final ITProdtechService pchService;
    final ITProdstatService pstatService;
    @Override
    public Object add(HttpServletRequest request, String json) {
        TProdproc t= JSON.parseObject(json,TProdproc.class);
        if(t.getId()>0){
            boolean bl=  updateById(t);
            if(!bl){
                return JsonResult.error(ErrorCode.ERR_200);
            }
        }else{
            t.setDate(new Date());
            boolean bl= save(t);
            if(!bl){
                return JsonResult.error(ErrorCode.ERR_504);
            }
        }
        if(!t.getIds().isEmpty()) {
            t.setMlist(getProdtechList(t.getIds()));
        }
        return JsonResult.success(t);
    }

    private List<TProdtech> getProdtechList(String ids) {
        QueryWrapper<TProdtech> qwc = new QueryWrapper<>();
        qwc.in("id", (Object[]) ids.split(","));
        List<TProdtech> list = pchService.list(qwc);
        // 使用 LinkedHashSet 保持 ids 的顺序并去除重复项
        List<String> idOrder = new ArrayList<>(new LinkedHashSet<>(Arrays.asList(ids.split(","))));
        // 按照 ids 的顺序对查询结果进行排序
        List<TProdtech> sortedList = list.stream()
                .sorted(Comparator.comparingInt(item -> idOrder.indexOf(String.valueOf(item.getId()))))
                .collect(Collectors.toList());

        Set<String> bnSet = new HashSet<>();
        for (TProdtech t : sortedList) {
            if (!t.getEqbn().isEmpty()) {
                bnSet.add(t.getEqbn());
            }
        }
        if (!bnSet.isEmpty()) {
            QueryWrapper<TProdstat> qws = new QueryWrapper<>();
            qws.in("eqbn", bnSet);
            qws.in("stat", 1, 2);
            List<TProdstat> prodstatList = pstatService.list(qws);

            Map<String, List<TProdstat>> bnToProdstatMap = prodstatList.stream()
                    .collect(Collectors.groupingBy(TProdstat::getEqbn));

            for (TProdtech t : sortedList) {
                if (!t.getEqbn().isEmpty() && bnToProdstatMap.containsKey(t.getEqbn())) {
                    t.setEqtask(bnToProdstatMap.get(t.getEqbn()));
                }
            }
        }
        return sortedList;
    }

    @Override
    public Object get(HttpServletRequest request,  Integer id, String bn) {
        if(id!=null){
            TProdproc t= getById(id);
            if(t!=null){
                if(!t.getIds().isEmpty()) {
                    t.setMlist(getProdtechList(t.getIds()));
                }
            }
            return JsonResult.success(t);
        }
        if( bn!=null){
            QueryWrapper<TProdproc> qw=new QueryWrapper<>();
            qw.like("bn",bn);
            List<TProdproc> list=list(qw);
            if(!list.isEmpty()) {
                for (TProdproc t : list) {
                    if (!t.getIds().isEmpty()) {
                        t.setMlist(getProdtechList(t.getIds()));
                    }
                }
            }
            return JsonResult.success(list);
        }
        return JsonResult.error(ErrorCode.ERR_200);
    }

    @Override
    public Object del(HttpServletRequest request, Integer id) {
        boolean bl= removeById(id);
        if(bl) {
            return JsonResult.success();
        }
        return JsonResult.error(ErrorCode.ERR_200);
    }
}
